'use strict';
const Service = require('egg').Service;
const crypto = require('crypto');
const md5 = require('md5');
const rp = require('request-promise');

class weixinService extends Service {
    constructor(ctx) {
      super(ctx);
    } 
    async login(code) 
    {
        try {
          // 获取 session
          const options = {
            method: 'GET',
            url: 'https://api.weixin.qq.com/sns/jscode2session',
            qs: {
              grant_type: 'authorization_code',
              js_code: code,
              secret: this.config.weixin.secret,
              appid: this.config.weixin.appid
            }
          };
          
          let sessionData = await rp(options);
          console.log(sessionData);
          sessionData = JSON.parse(sessionData);
          if (!sessionData.openid) {
            return { errno: sessionData.errcode, errmsg: sessionData.errmsg, data: null };
          }
          return { errno: 0, errmsg: '', data: sessionData };
        } catch (e) {
          return { errno: 400, errmsg: '微信登录失败：' + e.message, data: null };
        }
    }
}


  
module.exports = weixinService;